package com.yxjx.duoxue.payment;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;

import com.baidu.location.ad;
import com.yxjx.duoxue.BaseActionBarActivity;
import com.yxjx.duoxue.R;
import com.yxjx.duoxue.customview.LineGridView;
import com.yxjx.duoxue.customview.YxGridView;
import com.yxjx.duoxue.customview.YxListView;
import com.yxjx.duoxue.datamodel.DMCourseCategory;
import com.yxjx.duoxue.global.Globals;
import com.yxjx.duoxue.utils.UIHelper;
import com.yxjx.duoxue.utils.Utils;

/**
 * ListView 中的ViewPager必须使用固定的高度。坑爹！
 * @author mengmengchen
 * NOTICE: 是一个ScrolleView作为最外层控件时，设置的background不起作用，坑！
 */
public class KidInfoSelectCoursesActivity extends BaseActionBarActivity {
	
	public static final String KEY_SELECT_COURSES = "KEY_SELECT_COURSES";
	private static final int POPUP_PAGE_ITEM_NUM = 9;
	private static final int DOUBLE_OFFSET = 30;
	private static final int SINGLE_OFFSET = 15;
	
	private static final int COLUMN_NUM_LEVEL_1 = 3;
	private static final int TYPE_POPUP_GIRD_COUNT = 2;
	private static final int TYPE_GRID_ROW = 0;
	private static final int TYPE_GRID_POPUP = 1;
	
	private YxGridView selectedLabelGrid;
	// ListView 实现的popup gridview 效果。
	private YxListView courseGrid;
	private SelectedCourseAdapter selectedLabelGridAdapter;
	private CourseGridLevel1Adapter courseGrid1Adapter;
	
	private ArrayList<DMCourseCategory> level2SelectedItems;
	public ArrayList<DMCourseCategory> processedData;
	// typeId, selected child count
	private HashMap<Integer, Integer> typeChildSelectedCount = new HashMap<Integer, Integer>();
	// cache level2 popup gridview's adapter.
	ArrayList<Level2GridAdapter> cachedLevel2Adapter = new ArrayList<Level2GridAdapter>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_kid_info_select_courses);
		customizeActionBarTitle("课程分类");
		
		selectedLabelGrid = (YxGridView) findViewById(R.id.selected_labels);
		selectedLabelGridAdapter = new SelectedCourseAdapter();
		courseGrid = (YxListView) findViewById(R.id.course_grid);
		courseGrid1Adapter = new CourseGridLevel1Adapter();
		selectedLabelGrid.setAdapter(selectedLabelGridAdapter);
		ArrayList<ArrayList<DMCourseCategory>> courseTypes = Globals.getInstance(this).getCourseTpes();
		courseGrid1Adapter.setData(courseTypes);
		courseGrid.setAdapter(courseGrid1Adapter);
		
		
		
		selectedLabelGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				level2SelectedItems.remove(arg2);
				updateSelectedState();
				selectedLabelGridAdapter.notifyDataSetChanged();
			}
		});
		
		level2SelectedItems = (ArrayList<DMCourseCategory>) getIntent().getSerializableExtra(KEY_SELECT_COURSES);
		if (level2SelectedItems == null) {
			level2SelectedItems = new ArrayList<DMCourseCategory>();
		}
		
		updateSelectedState();
	}
	
	private void addLevel2ItemToSelected(DMCourseCategory type, int index) {
		for (DMCourseCategory item : level2SelectedItems) {
			if (item.getType() == type.getType()) {
				return;
			}
		}
		level2SelectedItems.add(type);
		updateSelectedState();
		selectedLabelGridAdapter.notifyDataSetChanged();
	}
	
	public void selectCourses(View view) {
		if (level2SelectedItems == null || level2SelectedItems.size() < 1 || level2SelectedItems.size() > 5) {
			UIHelper.showTips(view, "请选择1～5门期望的课程类型");
			return;
		}
		Intent intent = new Intent();
		intent.putExtra(KEY_SELECT_COURSES, level2SelectedItems);
		setResult(RESULT_OK, intent);
		finish();
	}
	
	class SelectedCourseAdapter extends BaseAdapter {

		@Override
		public Object getItem(int arg0) {
			return null;
		}
		
		@Override
		public long getItemId(int arg0) {
			return 0;
		}
		
		@Override
		public int getCount() {
			return level2SelectedItems == null ? 0 : level2SelectedItems.size();
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(KidInfoSelectCoursesActivity.this).inflate(R.layout.item_grid_course_selected, null);
			} else {
				ret = arg1;
			}
			
			UIHelper.setText(ret, R.id.text, level2SelectedItems.get(arg0).getStr());
			return ret;
		}
	}
	
	class CourseGridLevel1Adapter extends BaseAdapter {
		
		private ArrayList<ArrayList<DMCourseCategory>> courseTypes; // 每一行的data为长度为COLUMN_NUM_LEVEL_1的ArrayList
		private boolean showPopup = false;
		private int popupIndex = -1;
		private HashMap<Integer, Integer> itemIdMap;
		
		private DMCourseCategory getPopupItem() {
			if (popupIndex < 0 || courseTypes == null || courseTypes.size() == 0) {
				return null;
			}
			
			DMCourseCategory ret = getDataItemByIndex(popupIndex);
			
			return ret;
		}
		
		public int getPopupColumnIndex() {
			return getColumnIndex(popupIndex);
		}
 
		private DMCourseCategory getDataItemByIndex(int index) {
			int rowIndex  = getRowIndex(index);
			int columnIndex = getColumnIndex(index);
			DMCourseCategory ret = courseTypes.get(rowIndex).get(columnIndex);
			return ret;
		}

		private int getColumnIndex(int index) {
			return index % COLUMN_NUM_LEVEL_1;
		}
		

		private int getRowIndex(int index) {
			return index / COLUMN_NUM_LEVEL_1;
		}
		
		public void setData(ArrayList<ArrayList<DMCourseCategory>> data) {
			processedData = processData(data);
			courseTypes = assembleToThreeColumn(processedData);
			if (courseTypes == null || courseTypes.size() == 0) {
				return;
			}
			getItemIdMap();
			notifyDataSetChanged();
		}

		private void getItemIdMap() {
			itemIdMap = new HashMap<Integer, Integer>();
			int i = 0;
			for (ArrayList<DMCourseCategory>row : courseTypes) {
				for (DMCourseCategory item : row) {
					itemIdMap.put(item.getType(), i);
					i++;
				}
			}
		}
		
		@Override
		public int getViewTypeCount() {
			return TYPE_POPUP_GIRD_COUNT;
		}
		
		@Override
		public int getItemViewType(int position) {
			if (!showPopup) {
				return TYPE_GRID_ROW;
			} else {
				int selectedRow = getRowIndex(popupIndex);
				if (position == selectedRow + 1) {
					return TYPE_GRID_POPUP;
				} else {
					return TYPE_GRID_ROW;
				}
			}
		}
		
		@Override
		public int getCount() {
			return courseTypes.size() + (showPopup ? 1 : 0);
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret = null;
			if (getItemViewType(arg0) == TYPE_GRID_ROW) {
				ret = getItemRow(arg0, arg1);
			} else if (getItemViewType(arg0) == TYPE_GRID_POPUP) {
				ret = getItemPopup(getPopupItem());
			}
			return ret;
		}
		
		private View getItemRow(int position, View ret) {
			int actualPosition = getActualRowPosition(position);
			ArrayList<DMCourseCategory> rowData = courseTypes.get(actualPosition);
			if (ret == null) {
				ret = LayoutInflater.from(KidInfoSelectCoursesActivity.this)
						.inflate(R.layout.item_row_grid, null);
			}
			if (rowData.size() == 1) {
				handleColumnNumber1(rowData, ret);
			} else if (rowData.size() == 2) {
				handleColumnNumber2(rowData, ret);
			} else if (rowData.size() == 3) {
				handleColumnNumber3(rowData, ret);
			}
			return ret;
		}
		
		private int getActualRowPosition(int position) {
			if (!showPopup) {
				return position;
			} else {
				if (position <= getRowIndex(popupIndex)) {
					return position;
				} else {
					return position - 1;
				}
			}
		}

		private View getItemPopup(DMCourseCategory type) {
			return getPopWindowCustomView(type);
		}

		private void handleColumnNumber3(ArrayList<DMCourseCategory> rowData,
				View ret) {
			ret.findViewById(R.id.item1).setVisibility(View.VISIBLE);
			ret.findViewById(R.id.item2).setVisibility(View.VISIBLE);
			ret.findViewById(R.id.item3).setVisibility(View.VISIBLE);
			
			UIHelper.setText(ret.findViewById(R.id.item1), R.id.text, rowData.get(0).getStr());
			UIHelper.setText(ret.findViewById(R.id.item2), R.id.text, rowData.get(1).getStr());
			UIHelper.setText(ret.findViewById(R.id.item3), R.id.text, rowData.get(2).getStr());
			UIHelper.setClickListener(ret, R.id.item1, new ClickListener(rowData.get(0)));
			UIHelper.setClickListener(ret, R.id.item2, new ClickListener(rowData.get(1)));
			UIHelper.setClickListener(ret, R.id.item3, new ClickListener(rowData.get(2)));
			
			ret.findViewById(R.id.item1).findViewById(R.id.text).setSelected(isLevel1Selected(rowData.get(0)));
			ret.findViewById(R.id.item2).findViewById(R.id.text).setSelected(isLevel1Selected(rowData.get(1)));
			ret.findViewById(R.id.item3).findViewById(R.id.text).setSelected(isLevel1Selected(rowData.get(2)));

		}

		private void handleColumnNumber2(ArrayList<DMCourseCategory> rowData,
				View ret) {
			ret.findViewById(R.id.item1).setVisibility(View.VISIBLE);
			ret.findViewById(R.id.item2).setVisibility(View.VISIBLE);
			ret.findViewById(R.id.item3).setVisibility(View.INVISIBLE);
			
			UIHelper.setText(ret.findViewById(R.id.item1), R.id.text, rowData.get(0).getStr());
			UIHelper.setText(ret.findViewById(R.id.item2), R.id.text, rowData.get(1).getStr());
			UIHelper.setClickListener(ret, R.id.item1, new ClickListener(rowData.get(0)));
			UIHelper.setClickListener(ret, R.id.item2, new ClickListener(rowData.get(1)));
			
			ret.findViewById(R.id.item1).findViewById(R.id.text).setSelected(isLevel1Selected(rowData.get(0)));
			ret.findViewById(R.id.item2).findViewById(R.id.text).setSelected(isLevel1Selected(rowData.get(1)));
			
		}

		private void handleColumnNumber1(ArrayList<DMCourseCategory> rowData,
				View ret) {
			ret.findViewById(R.id.item1).setVisibility(View.VISIBLE);
			ret.findViewById(R.id.item2).setVisibility(View.INVISIBLE);
			ret.findViewById(R.id.item3).setVisibility(View.INVISIBLE);
			
			UIHelper.setText(ret.findViewById(R.id.item1), R.id.text, rowData.get(0).getStr());
			UIHelper.setClickListener(ret, R.id.item1, new ClickListener(rowData.get(0)));
			
			ret.findViewById(R.id.item1).findViewById(R.id.text).setSelected(isLevel1Selected(rowData.get(0)));
		}
		
		class ClickListener implements View.OnClickListener {
			
			private DMCourseCategory type;
			
			public ClickListener(DMCourseCategory item) {
				type = item;
			}
			
			@Override
			public void onClick(View arg0) {
				if (type != null) {
					int newPopupIndex = itemIdMap.get(type.getType());
					
					if (newPopupIndex == popupIndex) {
						showPopup = !showPopup;
						emptyLevel2Adapters();
					} else {
						showPopup = true;
						popupIndex = newPopupIndex;
					}
					notifyDataSetChanged();
				}
			}
		}
	}
	

	// 处理data, 原数据为： 声乐舞蹈， 全部， sub1，sub2，sub3
	// 				     体育运动，全部，sub1，sub2，
	//					 其他，全部，sub1
	// 处理后的数据：		 声乐舞蹈｛ sub：｛全部， sub1，sub2，sub3｝
	// 				     体育运动，｛全部，sub1，sub2｝
	//					 其他，｛全部，sub1｝
	private ArrayList<DMCourseCategory> processData(
			ArrayList<ArrayList<DMCourseCategory>> data) {
		if (data == null) {
			return null;
		}
		ArrayList<DMCourseCategory> ret = new ArrayList<DMCourseCategory>();
		for (int i = 0; i < data.size(); i++) {
			DMCourseCategory firstItem = new DMCourseCategory(data.get(i).get(0));
			if (firstItem.getType() == -1) {
				continue;
			}
			ArrayList<DMCourseCategory> subCategories = getSubCategories(data.get(i));
			firstItem.setSubCategories(subCategories);
			// 将自己加为sub item
			firstItem.getSubCategories().add(firstItem);
			ret.add(firstItem);
		}
		return ret;
	}
	
	// 将 1，2，3，4，5，6，7
	// 处理为:  [1,2,3]
	//         [4,5,6]
	//		   [7]
	private ArrayList<ArrayList<DMCourseCategory>> assembleToThreeColumn(
			ArrayList<DMCourseCategory> data) {
		if (data == null) {
			return null;
		}
		ArrayList<ArrayList<DMCourseCategory>> ret = new ArrayList<ArrayList<DMCourseCategory>>();
		int size = data.size();
		int row = size / COLUMN_NUM_LEVEL_1;
		int reminder = size % COLUMN_NUM_LEVEL_1;
		row += (reminder == 0 ? 0 : 1);
		for (int rowIndex = 0; rowIndex < row; rowIndex++) {
			ArrayList<DMCourseCategory> rowData = new ArrayList<DMCourseCategory>();
			for (int columnIndex = 0; columnIndex < COLUMN_NUM_LEVEL_1 && (rowIndex * COLUMN_NUM_LEVEL_1 + columnIndex) < size; columnIndex++) {
				int index = rowIndex * COLUMN_NUM_LEVEL_1 + columnIndex;
				rowData.add(data.get(index));
			}
			ret.add(rowData);
		}
		return ret;
	}

	private ArrayList<DMCourseCategory> getSubCategories(ArrayList<DMCourseCategory> row) {
		if (row == null || row.size() <=2) {
			return null;
		}
		ArrayList<DMCourseCategory> ret = new ArrayList<DMCourseCategory>();
		for (int i = 2; i < row.size(); i++) {
			ret.add(row.get(i));
		}
		return ret;
	}
	
	// ViewPager indicator
	private void initAdIndicator(LinearLayout indicator, int count) {
		indicator.removeAllViews();
		for (int i = 0; i < count; i++) {
			ImageView child = new ImageView(selectedLabelGrid.getContext());
			child.setImageResource(R.drawable.selector_circle_indicator);
			indicator.addView(child);
		}
	}
	
	private void setAdIndicator(LinearLayout indicator, int index) {
		for (int i = 0; i < indicator.getChildCount(); i++) {
			if (i == index) {
				indicator.getChildAt(i).setSelected(true);
			} else {
				indicator.getChildAt(i).setSelected(false);
			}
		}
	}
	
	/////////////////////////////////////////////////////////////////////////////
	// [start] 二级courseType dialog .
	/////////////////////////////////////////////////////////////////////////////
	private PopupWindow mPopupWindow;
	private OnTouchListener onPopWindowTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (mPopupWindow != null && mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
				mPopupWindow = null;
			}
			return false;
		}
	};
	
	private View getPopWindowCustomView(DMCourseCategory type) {
		View ret = LayoutInflater.from(KidInfoSelectCoursesActivity.this)
				.inflate(R.layout.segment_viewpager_course_types_level2, null);
		
		ViewPager viewPager = (ViewPager) ret.findViewById(R.id.pager);
		final LinearLayout indicator = (LinearLayout) ret.findViewById(R.id.indicator);
		MyViewPagerAdapter paerAdapter = new MyViewPagerAdapter(type);
		viewPager.setAdapter(paerAdapter);
		if (type != null && type.getSubCategories() != null) {
			int size = type.getSubCategories().size();
			final int stepLen = paerAdapter.getViewPagerCount();
			initAdIndicator(indicator, stepLen);
			viewPager.setOnPageChangeListener(new OnPageChangeListener() {
				
				@Override
				public void onPageSelected(int arg0) {
				}
				
				@Override
				public void onPageScrolled(int arg0, float arg1, int arg2) {
					if (arg1 == 0.0) {
						int indicatorIndex = arg0 % stepLen;
						setAdIndicator(indicator, indicatorIndex);
					}
				}
				
				@Override
				public void onPageScrollStateChanged(int arg0) {
				}
			});
		}
		setHeadIndicator(ret);
		
		return ret;
	}
	
	
	
	private void setHeadIndicator(View ret) {
		int index = courseGrid1Adapter.getPopupColumnIndex();
		View container = ret.findViewById(R.id.indicator_selections);
		container.findViewById(R.id.selection1).setVisibility(index == 0 ? View.VISIBLE : View.INVISIBLE);
		container.findViewById(R.id.selection2).setVisibility(index == 1 ? View.VISIBLE : View.INVISIBLE);
		container.findViewById(R.id.selection3).setVisibility(index == 2 ? View.VISIBLE : View.INVISIBLE);
	}

	class MyViewPagerAdapter extends PagerAdapter {
		
		private DMCourseCategory mType;
		public MyViewPagerAdapter(DMCourseCategory type) {
			mType = type;
		}

		@Override
		public int getCount() {
			if (mType == null || mType.getSubCategories() == null || mType.getSubCategories().size() == 0) {
				return 0;
			}
			int count = getViewPagerCount();
			return count;
		}

		public int getViewPagerCount() {
			ArrayList<DMCourseCategory> subs = mType.getSubCategories();
			int pageNum = subs.size() / POPUP_PAGE_ITEM_NUM;
			int reminder = subs.size() % POPUP_PAGE_ITEM_NUM;
			int count = pageNum + (reminder == 0 ? 0 : 1);
			return count;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View item = LayoutInflater.from(KidInfoSelectCoursesActivity.this)
					.inflate(R.layout.segment_grid_course_types_level2, null);
			LineGridView grid = (LineGridView) item.findViewById(R.id.grid);
			final Level2GridAdapter adapter = new Level2GridAdapter(mType, position);
			grid.setAdapter(adapter);
			
			grid.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					addLevel2ItemToSelected(adapter.getTypes().get(arg2), arg2);
					adapter.notifyDataSetChanged();
					
				}
			});
			
			container.addView(item, position);
			addLevel2Adapters(adapter);
			return container.getChildAt(position);
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			super.destroyItem(container, position, object);
		}
	}
	
	class Level2GridAdapter extends BaseAdapter {
		
		private ArrayList<DMCourseCategory> types;
		
		public ArrayList<DMCourseCategory> getTypes() {
			return types;
		}

		public Level2GridAdapter(DMCourseCategory type, int position) {
			ArrayList<DMCourseCategory> subtypes = type.getSubCategories();
			// position * PAGE_ITEM_NUM ~ ((position + 1) * PAGE_ITEM_NUM - 1)
			types = new ArrayList<DMCourseCategory>();
			for (int i = position * POPUP_PAGE_ITEM_NUM; (i < (position + 1) * POPUP_PAGE_ITEM_NUM) && (i < subtypes.size()); i++) {
				types.add(subtypes.get(i));
			}
		}

		@Override
		public int getCount() {
			return types.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			View ret;
			if (arg1 == null) {
				ret = LayoutInflater.from(KidInfoSelectCoursesActivity.this)
						.inflate(R.layout.item_course_grid_level_2, null);
			} else {
				ret = arg1;
			}
			
			DMCourseCategory item = types.get(arg0);
			if (item.getSubCategories() != null && item.getSubCategories().size() > 0) {
				UIHelper.setText(ret, R.id.text, "全部");
			} else {
				UIHelper.setText(ret, R.id.text, item.getStr());
			}
			ret.findViewById(R.id.text).setSelected(isLevel2Selected(item));
			return ret;
		}
	}
	
	private void initPopupWindow(int sugW, int sugH, DMCourseCategory type) {
		View customView = getPopWindowCustomView(type);
		mPopupWindow = new PopupWindow(customView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		customView.setOnTouchListener(onPopWindowTouchListener);

		mPopupWindow.setTouchable(true);
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.setFocusable(true);
//		mPopupWindow.setBackgroundDrawable(getResources().getDrawable(
//				android.R.color.transparent));
		ColorDrawable dw = new ColorDrawable(0x90000000);
		mPopupWindow.setBackgroundDrawable(dw);

		Window window = getWindow();
		WindowManager.LayoutParams lp = window.getAttributes();
		lp.dimAmount = .5f;
		window.setAttributes(lp);
	}
	
	private void tryShowDialog(View view, DMCourseCategory type) {
		if (type == null) {
			return;
		}
		// 获取期望window大小
		int[] sizes = Utils.getDisplayWidthHeight(this);
		int[] viewPosition = new int[2];
		view.getLocationOnScreen(viewPosition);
		int windowHeight = getResources().getDimensionPixelSize(R.dimen.course_subtypes_window_height);
//		int windowHeight = sizes[1] - viewPosition[1] - view.getHeight();
		
		if (mPopupWindow == null || !mPopupWindow.isShowing()) {
			initPopupWindow((int) (sizes[0] - DOUBLE_OFFSET),
					windowHeight, type);

			mPopupWindow.showAsDropDown(view, 0, 0);
		}
	}
	
	private void dismissPopupWindowIfHave() {
		if (mPopupWindow != null && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
		}
	}
	/////////////////////////////////////////////////////////////////////////////
	// [end] 二级courseType dialog .
	/////////////////////////////////////////////////////////////////////////////
	private boolean isLevel2Selected(DMCourseCategory type) {
		if (type == null || level2SelectedItems == null || level2SelectedItems.size() == 0) {
			return false;
		}
		for (DMCourseCategory item : level2SelectedItems) {
			if (item.getType() == type.getType()) {
				return true;
			}
		}
		return false;
	}
	
	private boolean isLevel1Selected(DMCourseCategory type) {
		if (type == null) {
			return false;
		}
		if (typeChildSelectedCount.containsKey(type.getType())) {
			return typeChildSelectedCount.get(type.getType()) > 0;
		}
		return false;
	}
	
	/**
	 * update selected child count of every item.
	 * called when level2SelectedItems changes.
	 */
	private void updateSelectedState() {
		if (processedData == null) {
			return;
		}
		
		for (DMCourseCategory level1Item : processedData) {
			typeChildSelectedCount.put(level1Item.getType(), 0);
			ArrayList<DMCourseCategory> subs = level1Item.getSubCategories();
			if (subs != null) {
				int count = 0;
				for (DMCourseCategory subItem : subs) {
					count += (isLevel2Selected(subItem) ? 1 : 0);
				}
				typeChildSelectedCount.put(level1Item.getType(), count);
			}
		}
		
		courseGrid1Adapter.notifyDataSetChanged();
		updateLevel2Adapters();
		
	}
	
	private void addLevel2Adapters(Level2GridAdapter adapter) {
		if (cachedLevel2Adapter == null) {
			cachedLevel2Adapter = new ArrayList<Level2GridAdapter>();
		}
		cachedLevel2Adapter.add(adapter);
	}
	
	private void emptyLevel2Adapters() {
		cachedLevel2Adapter = new ArrayList<Level2GridAdapter>();
	}
	
	private void updateLevel2Adapters() {
		if (cachedLevel2Adapter != null) {
			for (Level2GridAdapter item : cachedLevel2Adapter) {
				item.notifyDataSetChanged();
			}
		}
	}
	
}
